<?php

use Illuminate\Support\Facades\DB;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Support\Facades\Session;
use App\Register;
use App\User;
class Tools
{
    /**
     * @return string
     * 检测权限，粒度是按钮
     */
    public static function checkNode($mgid, $url)
    {
        $rules   = DB::select("SELECT rules from zhyl_sys_role where role_id in (
                        SELECT role_id from zhyl_sys_mgrole where mg_id=?)", [$mgid]);
        $rulearr = explode(',', $rules[0]->rules);//获取用户所拥有的rules
        $ruleid  = DB::select("SELECT id from zhyl_sys_rule where name='$url'")[0]->id;//获取当前路由的规则id
        return in_array($ruleid, $rulearr);
    }

    /**
     * @param $url
     * @return string
     * curl get请求方式
     */
    public static function curlget($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $data = "";
        if (curl_exec($ch)) {
            $data = curl_multi_getcontent($ch);
        }
        curl_close($ch);
        return $data;
    }

    /**
     * @param $url
     * @param array $fields
     * @return string
     * curl post请求方式
     */
    public static function culpost($url, $fields = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        if ($fields) {
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($data_string))
            );
        }
        $data = "";
        if (curl_exec($ch)) {
            $data = curl_multi_getcontent($ch);
        }
        curl_close($ch);
        return $data;
    }


    /**
     * 生成唯一的商品ID码
     * @param int $start
     * @param int $end
     * @param int $length
     * @return array
     */
    public static function get_rand_number($length, $seed)
    {
        $token        = "";
        $codeAlphabet = "abcdefghijklmnopqistuvwxyz";
        $codeAlphabet .= "0123456789";

        mt_srand($seed);      // Call once. Good since $application_id is unique.

        for ($i = 0; $i < $length; $i++) {
            $token .= $codeAlphabet[mt_rand(0, strlen($codeAlphabet) - 1)];
        }
        return $token;
    }

    public static function captcha()
    {
        $builder = new CaptchaBuilder;
        //可以设置图片宽高及字体
        $builder->build($width = 250, $height = 70, $font = null);
        //获取验证码的内容
        $phrase = $builder->getPhrase();
        //把内容存入session
        Session::flash('CAPTCHA_IMG', $phrase);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();
    }

    /**
     * 电话等规则匹配
     * @field phone、email、captcha、password/password2/password3
     */
    public static function field_patten($field, $request)
    {
        switch ($field) {
            case 'phone':
                $res = !preg_match("/^(1(([35789][0-9])|(47)))\d{8}$/", $request->phone) ? false : true;
                break;
            case 'email':
                $res = !preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/", $request->email) ? false : true;
                break;
            case "captcha":
                $res = $request->validcode != (Session::get("CAPTCHA_IMG")) ? false : true;
                break;
            case "password2":
                $res = !preg_match("^[_0-9a-z]{6,16}$", $request->password2) ? false : true;
                break;
        }
        return $res;
    }

    public static function ishava_field($request)
    {
        if (!$request->phone) {
            $res = return_msg("", "fail", "手机号不能为空");
        } else if (!$request->email) {
            $res = return_msg("", "fail", "邮箱不能为空");
        } else if (!$request->validcode) {
            $res = return_msg("", "fail", "验证码不能为空");
        } else if ($request->password2) {
            $res = return_msg("", "fail", "密码不能为空");
        } else if ($request->password3) {
            $res = return_msg("", "fail", "确认密码不能为空");
        }
        return $res;
    }

    /**
     * 根据前台用户登陆的id，获取用户数据
     * getUserInfo
     */
    public static function getUserInfo()
    {
        $userid = Session::get("userid");
        return isset($userid)?User::find($userid):null;
    }

    /**
     * 生成唯一的订单号
     * @param int $unique
     * @return $order_id
     */
    private static function gettradeno($unique = 0)
    {
        //生成24位唯一订单号码，格式：YYYY-MMDD-HHII-SS-NNNN,NNNN-CC，
        //其中：YYYY=年份，MM=月份，DD=日期，HH=24格式小时，II=分，SS=秒，NNNNNNNN=随机数，CC=检查码
        //订购日期
        $order_date = date('Y-m-d');
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
        return $order_id;

    }

    /**
     * 产生订单
     * @param  $tradeno 订单号(日期+)
     *
     */
    public static function settrade()
    {
        return self::gettradeno();
    }

    /**
     * 在订单表插入订单(可能支付/未支付)
     */
    public static function insertpayorder()
    {


    }

    /**
     * 返回一维数组
     * @param $sql语句
     * @param $params 参数
     */
    public static function find(string $sql="", array $params=[]):array
    {
        $info = DB::select($sql, $params);
        $arr  = [];
        if ($info) {
            foreach ($info[0] as $k => $v) {
                $arr = [$k=>$v];
            }
        } else {
            $arr = [];
        }
        return $info;
    }

    /**
     * 返回二维数组
     * @param $sql sql语句
     * @param @params 需要用到的参数
     * select
     */
    public static function select(string $sql, array $params=[]):array
    {

        return DB::select($sql, $params);
    }

    /**
     * 获取session
     * @param $param 参数
     * @return mixed
     * getSession
     */
    public static function getSession(string $param=""):string
    {
        return Session::get($param);
    }

    /**
     * 获取后台用户数据
     * @param $mgid
     * getManagerInfo
     */
    public static function getManagerInfo(){
        return DB::select("select * from zhyl_sys_manager where mg_id=?",[Session::get('mgid')])[0];

    }
}

